package applications.callcost;

import java.text.DecimalFormat;
import java.util.Timer;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.IBinder;
import android.provider.CallLog;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.widget.Toast;
import applications.callcost.listeners.PhoneListener;

public class CallListenerService extends Service{

	PhoneListener phoneListener;
	TelephonyManager mgr;
	Resources res;
	Timer sms;
	
	final String PREFS_NAME = "prefs";
	final String ADDITIONAL_ON="ao";
	
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	public void onCreate() {
        super.onCreate();
        
        res = getResources();
        
        sms=new Timer();
        sms.schedule(new SmsReceiver(getApplicationContext()), 0, 60000);
        
        phoneListener=new PhoneListener(this);
        
        mgr=(TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
        
        try{
        	mgr.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
        }catch(Exception e){
        	Toast toast = Toast.makeText(getApplicationContext(), res.getString(R.string.permerror), Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER, 0, 0);
        	toast.show();
            return;
        }
        
        Toast toast = Toast.makeText(getApplicationContext(), res.getString(R.string.monitoron), Toast.LENGTH_SHORT);
        toast.show();
        
	}

	public void onDestroy() {
        super.onDestroy();
        mgr.listen(phoneListener, PhoneStateListener.LISTEN_NONE);
        sms.cancel();
        Toast toast = Toast.makeText(getApplicationContext(), res.getString(R.string.monitoroff), Toast.LENGTH_SHORT);
        toast.show();
	}

	public void showCost(){
		
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor   = settings.edit();
		
		ContentResolver cr=getContentResolver();

		//Make the query. 
		Cursor cursor = cr.query(
			CallLog.Calls.CONTENT_URI,
            null, // Which columns to return (all)
            null, // Which rows to return (all)
            null, // Selection arguments (none)
            null  // Order by call time (default==descending)
            );
		
		cursor.moveToLast();
		
		int type=cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
		if(type==CallLog.Calls.INCOMING_TYPE || type==CallLog.Calls.MISSED_TYPE)
			return;
		
		
		int scatto, costPerMin, addcost, addtime;
		double cost, time;
		
		time=cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DURATION));
		costPerMin=settings.getInt(CallCostMain.MINUTE_COST, 0);
		addcost=settings.getInt(CallCostMain.ADDITIONAL_COST, 0);
		addtime=settings.getInt(CallCostMain.ADDITIONAL_TIME, 0);
		scatto=settings.getInt(CallCostMain.SCATTO, 0);
		
		//cost=scatto + tempo(min)*costo(min) + tempo(sec)/tempocostoagg(sec) * costoadd
		cost=scatto + (time/60*costPerMin);
		if(addtime!=0 && addcost!=0 && settings.getBoolean(ADDITIONAL_ON, false))
			cost+=( ( (int)(time) ) /addtime )*addcost;
		
		float credit=settings.getFloat(CallCostMain.CREDIT_LEFT, 0);
		
		credit-=((float)cost)/100;
		
		editor.putFloat(CallCostMain.CREDIT_LEFT, credit);
		editor.commit();
		
		if(time<=0)
			return;
		
		//toast notification
		if(settings.getBoolean("dialog", true)){
			Toast toast = Toast.makeText(getApplicationContext(),
					res.getString(R.string.callcost) +" "+ 
					(new DecimalFormat("0.##").format((double)cost/100)) + "\n"+res.getString(R.string.calltime) + " " +
					(int)(time) + " " +res.getString(R.string.seconds),
					Toast.LENGTH_LONG);
	        toast.show();
		}
		
		//status bar notification
		if(settings.getBoolean("notification", true)){
			NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			Notification notification = new Notification(R.drawable.warning,res.getString(R.string.credito) +": "+ 
					credit , System.currentTimeMillis());
			
			CharSequence contentTitle = res.getString(R.string.callcost) +" "+ 
			(new DecimalFormat("0.##").format((double)cost/100));
			CharSequence contentText = res.getString(R.string.credito) +": "+ 
			credit;
			
			Intent notificationIntent = new Intent(this, CallListenerService.class);
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

			notification.setLatestEventInfo(getApplicationContext(), contentTitle, contentText, contentIntent);
			notification.flags=Notification.FLAG_AUTO_CANCEL;
			mNotificationManager.notify(1, notification);
		}
	}
}
